<template>
	<app-layout>
		<view class="page" :style="{ height: height }">
			<view class="swiper" :style="containerStyle">
				<block v-for="(item, index) in videoList" :key="index">
					<video-new
							class="video"
							:video_id="item.video_id"
							:video_url="item.video_url"
							:height="height"
							:width="width"
							:play="item.flag"
							:cur_index="cur_index"
							:style="{ height: height, width: width }"
					></video-new>
				</block>
			</view>
			<view class="close" @click.stop="close">
				<image class="image" src="/static/image/icon/video-close.png"></image>
			</view>
			<view
					class="cover-view-marks"
					:style="{ height: height, width: width }"
					@click.stop="clickVideo"
					@touchmove="ListTouchMove"
					@touchend.stop="ListTouchEnd"
					@touchstart="ListTouchStart"
			>
			</view>
			<view class="operating ">
				<view class="dir-left-nowrap cross-bottom">
					<view class="left dir-left-nowrap main-between">
						<view class="up-down-goods">
							<view class="item" @click="previous">上一件商品</view>
							<view class="item down" @click="next">下一件商品</view>
						</view>
						<view class="goods-list">
							<view class="scroll" :style="{bottom: (getEmpty+157) + 'rpx'}" v-show="goodBool">
								<view  class="scroll-view">
									<view class="item-good dir-left-nowrap"  @click="routeGo(goods_list[cur_index].page_url)">
										<view class="image-view cover-pic">
											<image class="cover-pic " :src="goods_list[cur_index].cover_pic"></image>
											<view>视频同款</view>
										</view>
										<view class="content dir-top-nowrap main-between">
											<view class="name t-omit-two">{{goods_list[cur_index].name}}</view>
											<view class="pri-but dir-left-nowrap main-between cross-bottom">
												<view>
													<view class="dir-left-nowrap">
														<!-- 会员价 -->
														<view class="member-price" v-if="goods_list[cur_index].is_level == 1 && goods_list[cur_index].is_negotiable != 1">
															<app-member-price
																	:price="goods_list[cur_index].level_price"
															></app-member-price>
														</view>
														<!-- 超级会员卡 -->
														<view class="app-sup-vip" v-if="goods_list[cur_index].vip_card_appoint.discount > 0">
															<app-sup-vip
																	:discount="goods_list[cur_index].vip_card_appoint.discount"
																	:is_vip_card_user="goods_list[cur_index].vip_card_appoint.is_vip_card_user"
															></app-sup-vip>
														</view>
													</view>
													<view class="pri">
														<text class="price">{{goods_list[cur_index].price_content}}</text>
														<text class="original">￥{{goods_list[cur_index].original_price}}</text>
													</view>
												</view>
												<view class="button" @click.stop="specification(goods_list[cur_index])"></view>
											</view>
										</view>
									</view>
								</view>
								<view class="triangle"></view>
							</view>
							<image class="image" src="/static/image/video-goods.png" @click="goodBool = !goodBool"></image>
						</view>
					</view>
					<view class="right dir-left-nowrap">
						<view class="but index" @click.stop="routeGo('/pages/index/index')">
							<view class="icon">
								<image class="image" src="/static/image/icon/video-index.png"></image>
							</view>
							<text>首页</text>
						</view>
						<view class="but cart" @click.stop="specification(goods_list[cur_index])">
							<view class="icon">
								<image class="image" src="/pages/goods/image/video-card.png"></image>
							</view>
							<text>加购</text>
						</view>
						<!-- <view class="but" >
							<view class="icon">
								<image class="image" src="/static/image/icon/video-share.png"></image>
							</view>
							<text>分享</text>
							<button class="share" open-type="share">
							</button>
						</view> -->
					</view>
				</view>
				<view class="empty" :style="{'height': getEmpty+'rpx'} ">
				</view>
			</view>
			<view class="attr">
				<app-attr ref="attr"
						  :goods="item"
						  :select-attr="selectAttr"
						  :attr-group-list="attrGroup"
						  :show="show"
						  :cartShow="cartShow"
						  :buyText="buyText"
						  :buyClick="buyBool"
						  :plugin="plugin"
						  :previewUrl="previewUrl"
						  :submitUrl="submitUrl"
						  @buyClick="buyClick"
						  @attrtap="onAttr"
						  @attr="attr"
				>
					<view slot="extra" v-if="sign === 'pintuan'">
						<app-pt-attr
								v-if="pt"
								:pintuan_groups="item.pintuan_groups"
								:selectGroupAttrId="selectGroupAttrId"
								@click="setGroupAttrID"
						></app-pt-attr>
					</view>
				</app-attr>
			</view>
			<view v-if="sign === 'pintuan' && show_pt">
				<app-iphone-x>
					<view class="pintuan dir-left-nowrap" slot="empty-area">
						<view class="single box-grow-1 dir-top-nowrap" @click="individual" v-if="item">
							<text class="app-text">单独购买</text>
						</view>
						<view class="tuan box-grow-1 dir-top-nowrap" @click="multiplayer">
							<text class="app-text">拼团</text>
						</view>
					</view>
				</app-iphone-x>
			</view>
		</view>
	</app-layout>
</template>

<script>
    import {mapGetters} from 'vuex';
    import videoNew from '../../components/page-component/goods/app-goods-video.vue';
    import appMemberPrice from '../../components/page-component/app-member-mark/app-member-price.vue';
    import appSupVip from '../../components/page-component/app-sup-vip/app-sup-vip.vue';
    import appAttr from '../../components/page-component/app-attr/app-attr.vue';
    import appIphoneX from '../../components/basic-component/app-iphone-x/app-iphone-x.vue';
    import appPtAttr from '../../components/page-component/app-pt-attr/app-pt-attr.vue';
    import allPay from './all-pay.js';

    export default {
        components: {
            videoNew,
            appPtAttr,
            'app-member-price': appMemberPrice,
            'app-sup-vip': appSupVip,
            'app-attr': appAttr,
            'app-iphone-x': appIphoneX,
        },
        data() {
            return {
                buyText: '立即购买',
                sign: '',
                cartShow: 1,
                plugin: '',
                buyBool: false,
                previewUrl: '',
                submitUrl: '',
                show_pt: false,
				pt: true,
				selectGroupAttrId: -1,
				pintuan_groups:[],
				appAttr: {},

                translateX: '10',
                height: '667px',
                cur_index: null,
                width: '',
                sysheight: 0,
                containerStyle: 'transform:translateY(0px)',
                distance: 0,
                listTouchStartY: 0,
                listTouchDirection: null,
                scroll: false,
                videoList: [],
                clicktime:0,
                goodBool: false,
	            goods_list: [],
				page: 1,
				goods_id: 0,
				show: 0,
				item: null,
				selectAttr: {},
				attrGroup: [],
				ne: 0,
				pre: 0,

            };
        },
		computed: {
			...mapGetters('iPhoneX', {
				getEmpty: 'getEmpty'
			}),
		},
        onLoad(options) {
        	this.goods_id = options.goods_id;
        	this.sign = options.sign;

        	switch (this.sign) {
				case "advance":
					this.cartShow = 0;
					this.buyText = '支付定金';
					this.buyBool = true;
					break;
				case "booking":
					this.cartShow = 0;
					this.buyText = '立即预约';
					this.plugin = 'booking';
					this.submitUrl = this.$api.book.order_submit;
					this.previewUrl = this.$api.book.order_preview;
					break;
				case "miaosha":
					this.submitUrl = this.$api.miaosha.order_submit;
					this.previewUrl = this.$api.miaosha.order_preview;
					break;
				case "pintuan":
					this.$request({
						url: this.$api.pt.detail,
						data: {
							id: this.goods_id,
							group_id: 0,
						}
					}).then((res) => {
						this.item = res.data.detail;
						this.selectGroupAttrId = this.item.pintuan_groups[0].id;

                    });
                    break;
                case "integral_mall":
                    this.cartShow = 0;
                    this.buyText = '立即兑换';
                    this.submitUrl = this.$api.integral_mall.order_submit;
                    this.previewUrl = this.$api.integral_mall.order_preview;
                    break;
                case "step":
                    this.cartShow = 0;
                    this.buyText = '立即兑换';
                    this.submitUrl = this.$api.step.order_submit;
                    this.previewUrl = this.$api.step.order_preview;
                    break;
                case "gift":
                    this.cartShow = 0;
                    this.buyBool = true;
                    this.buyText = '加入礼包';
                    break;
                case "mch":
                    this.submitUrl = this.$api.mch.order_submit;
                    this.previewUrl = this.$api.mch.order_preview;
                    break;
                default:
                    break;
            }

			this.getVideo(options.goods_id);
            let res = uni.getSystemInfoSync();
            this.height = `${res.windowHeight}px`;
            this.width = `${res.windowWidth}px`;
            this.sysheight = res.windowHeight;
        },
        onHide() {
            this.videoCtx = uni.createVideoContext(`video_${this.videoList[this.cur_index].video_id}`, this);
            this.videoCtx.pause();
        },
        onShow() {
			if (this.cur_index !== null && this.videoList[this.cur_index].flag) {
				this.videoCtx = uni.createVideoContext(`video_${this.videoList[this.cur_index].video_id}`, this);
				this.videoCtx.play();
			}
        },
        methods: {
			buyClick(data) {
				allPay(data, this.sign, this, this.goods_list[this.cur_index]);
				console.log(data);
			},
			submit() {
				let goods = this.item;
				let number = this.appAttr.number;
				let select_attr = this.selectAttr;
				if (!select_attr) {
					uni.showModal({
						title: '提示',
						content: '请先选择规格',
						showCancel: false
					});
					return false;
				}
				if (number <= 0) {
					uni.showModal({
						title: '提示',
						content: '商品数量不能为0',
						showCancel: false
					});
					return false;
				}
				if (!goods) {
					return false;
				}
				return true;
			},
			onAttr(data) {
				this.selectAttr = data;
			},
			specification(goods) {
				this.attrGroup = goods.attr_groups;
				this.show = Math.random();
				if (this.sign === 'pintuan') {
					this.show_pt = true;
					this.request_pt(this.selectGroupAttrId);
				} else {
					this.item = goods;
				}
			},
			setGroupAttrID(id) {
				this.selectGroupAttrId = id;
				this.selectAttr = {};
				this.request_pt(id);
			},
			attr(data) {
				this.appAttr = data;
				console.log(data);
			},
			buy() {
				if (!this.submit()) {
					return false;
				}
				let goods = this.item;
				let number = this.appAttr.number;
				let select_attr = this.selectAttr;
				let goods_attr_id = select_attr.id;
				let attr = [];
				for (let i in select_attr.attr_list) {
					attr.push({
						attr_id: select_attr.attr_list[i].attr_id,
						attr_group_id: select_attr.attr_list[i].attr_group_id,
					});
				}
				let mch_list = [];
				let mch = {
					mch_id: goods.mch_id ? goods.mch_id : 0,
					goods_list: []
				};
				mch.goods_list.push({
					id: goods.id,
					attr: attr,
					num: number,
					cat_id: 0,
					goods_attr_id: goods_attr_id
				});
				mch_list.push(mch);
				uni.navigateTo({
					url: '/pages/order-submit/order-submit?mch_list=' + JSON.stringify(mch_list),
				})
			},
			individual() {
				if (this.pt) {
					this.pt = false;
					this.selectAttr = {};
					this.request_pt(0);
				} else {
					if (Object.keys(this.selectAttr).length === 0) {
						uni.showToast({
							title: '请选择规格',
							icon: "none"
						})
					} else {
						this.buy();

					}
					console.log(this.selectAttr);
				}

			},
			multiplayer() {
				if (this.pt) {
					if (this.selectAttr && Object.keys(this.selectAttr).length === 0) {
						uni.showToast({
							title: '请选择规格',
							icon: "none"
						})
					} else if (this.selectAttr &&  Object.keys(this.selectAttr).length > 0) {
						console.log(this.selectAttr);
						let mch_id = this.item.mch_id;
						let mch_list = [];
						let goods = {
							id: this.item.id,
							attr: [],
							num: this.appAttr.number,
							goods_attr_id: this.selectAttr.id,
							cart_id: 0,
						};
						for (let i = 0; i < this.selectAttr.attr_list.length; i++) {
							let attr = {
								attr_id: this.selectAttr.attr_list[i].attr_id,
								attr_group_id: this.selectAttr.attr_list[i].attr_group_id,
							};
							goods.attr.push(attr);
						}
						mch_list.push({
							mch_id: mch_id,
							pintuan_order_id: 0,
							pintuan_group_id: this.selectGroupAttrId,
							goods_list: [goods],
						});
						console.log(mch_list);
						uni.navigateTo({
							url: `/pages/order-submit/order-submit?mch_list=${JSON.stringify(mch_list)}&preview_url=${encodeURIComponent(this.$api.pt.order_preview)}&submit_url=${encodeURIComponent(this.$api.pt.order_submit)}&order_page_url=/plugins/pt/order/order&plugin=pt`
						});

					}
				} else {
					this.selectAttr = {};
					this.pt = true;
					this.request_pt(this.selectGroupAttrId);
				}

			},
			async request_pt(group_id) {
				try {
					const response = await this.$request({
						url: this.$api.pt.detail,
						data: {
							id: this.goods_id,
							group_id: group_id,
						}
					});
					if (response.code === 0) {
						this.item = response.data.detail;
					}
				} catch(e) {
					throw new Error(e);
				}
			},
        	async getVideo() {

        		const res = await this.$request({
					url: this.$api.goods.goods_video_list,
					method: 'get',
					data: {
						goodsId: this.goods_id,
						page: this.page,
						limit: 3
					}
				});
        		if (res.code === 0) {
        			let data = res.data.list;
					for (let item of data) {
						this.videoList.push({
							video_id: item.id,
							video_url: item.video_url,
							flag: false,
						});
						this.goods_list.push(item);
					}
					if (this.cur_index == null) this.cur_index = 0;

					this.$nextTick().then(() => {
						this.videoList[this.cur_index].flag = true;
						this.videoCtx = uni.createVideoContext(`video_${this.videoList[this.cur_index].video_id}`, this);
						this.videoCtx.play();
					});
				}

			},
            routeGo(data) {
                uni.navigateTo({
	                url: data,
                })
            },
            close() {
				uni.redirectTo({
					url: this.goods_list[this.cur_index].page_url,
				});
            },
            lower() {
                console.log(1);
            },
            clickVideo(e) {
				this.goodBool = false;
                if(this.clicktime > 0 && e.timeStamp - this.clicktime < 200){
                    clearTimeout(this.han);
                }else{
                    let _this = this;
                    this.han = setTimeout(function() {
                        _this.videoList[_this.cur_index].flag = !_this.videoList[_this.cur_index].flag;
                    }, 200);
                }
                this.clicktime = e.timeStamp;
                return;
            },
            ListTouchStart(e) {
                this.listTouchStartY = e.changedTouches[0].pageY;
            },
            ListTouchMove(e) {
                this.listTouchDirection = this.listTouchStartY - e.changedTouches[0].pageY > 10 ? -1 : 0;
                this.listTouchDirection = e.changedTouches[0].pageY - this.listTouchStartY > 10 ? 1 : this.listTouchDirection;
                const distance = this.distance + e.changedTouches[0].pageY - this.listTouchStartY;
                if (distance > 0) return;
                if (Math.abs(this.listTouchStartY - e.changedTouches[0].pageY) < 2) {
                    this.listTouchDirection = null;
                }
            },
            ListTouchEnd(e) {
                this.handelVideo(e);
            },
            handelVideo(){
                if (this.cur_index == 0 && this.listTouchDirection == 1) {
                    return;
                }

                this.translateX = 10;
               
                if (this.scroll) return;
                if (!this.listTouchDirection) {
                    return;
                }
                const destination = this.listTouchDirection * this.sysheight + this.distance;
                if (destination > 0 || destination < -this.sysheight * (this.videoList.length - 1)) return;
                for (let item of this.videoList) {
                    item.flag = false;
                }

                this.animate(destination, this.listTouchDirection);
                this.cur_index = this.cur_index - this.listTouchDirection;
                this.videoList[this.cur_index].flag = true;

                //移动到最后一个加载新的列表
                if (this.videoList.length == this.cur_index + 1) {
					this.page++;
					this.getVideo();
                }
                this.listTouchDirection = null;
            },
            animate(des, direc) {
                let { distance } = this;
                return new Promise((resolve, reject) => {
                    this.scroll = true;
                    const temp = setInterval(() => {
                        if ((direc === -1 && des < distance) || (direc === 1 && des > distance)) {
                            distance += 100 * direc;
                            this.containerStyle = `transform:translateY(${distance}px)`;
                        } else {
                            clearInterval(temp);
                            distance = des;
                            this.distance = des;
                            this.containerStyle = `transform:translateY(${distance}px)`;
                            this.scroll = false;
                            resolve();
                        }
                    }, 20);
                });
            },

            previous() {
        		if (this.cur_index === 0) return;

				for (let item of this.videoList) {
					item.flag = false;
				}
				this.distance =this.distance + this.sysheight;
				let distance = this.distance;
				this.cur_index = this.cur_index - 1;
				this.containerStyle = `transform:translateY(${distance}px)`;
				clearTimeout(this.pre);
				this.pre = setTimeout(() => {
					this.videoList[this.cur_index].flag = true;
				}, 300);
            },
	        
            next() {
				if (this.cur_index + 1 === this.videoList.length) {
					uni.showToast({
						title: '无更多视频',
						icon: 'none'
					});
					return
				}

                this.distance = this.distance - this.sysheight;
                let distance = this.distance;

                this.containerStyle = `transform:translateY(${distance}px)`;

                clearTimeout(this.ne);
                this.ne = setTimeout(() => {
					this.videoList[this.cur_index].flag = false;
					this.cur_index = this.cur_index + 1;
					this.videoList[this.cur_index].flag = true;
				});

                if (this.videoList.length < this.cur_index + 2) {
                    this.page++;
                    this.getVideo();
                }
            }
        },

		onShareAppMessage() {
			return this.$shareAppMessage({
				title: this.goods_list[this.cur_index].app_share_title ? this.goods_list[this.cur_index].app_share_title : this.goods_list[this.cur_index].name,
				imageUrl: this.goods_list[this.cur_index].app_share_pic ? this.goods_list[this.cur_index].app_share_pic :  this.goods_list[this.cur_index].cover_pic,
				path: this.goods_list[this.cur_index].page_url.split('?')[0],
				params: {
					id: this.goods_list[this.cur_index].id,
					mch_id: this.goods_list[this.cur_index].mch_id
				}
			});
		},
		watch: {
			appAttr: {
        		handler(data) {
        			if (data.display === 'none') {
        				this.show_pt = false;
						// this.selectAttr = {};
					}
				}
			}
		}
    };
</script>

<style lang="scss">
	.empty {
		width: #{750upx};
	}
	.page {
		flex: 1;
		overflow: hidden;
		background-color: #000;
	}
	.operating {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		z-index: 1402;
	}
	.left {
		margin-left: #{26upx};
		width: #{410upx};
	}
	.right {
		margin-right: #{26upx};
	}
	.attr {
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 1403;
	}
	.up-down-goods {
		.item {
			width: #{266upx};
			height: #{60upx};
			border-radius: #{16upx};
			background-color: rgba(51,51,51,.4);
			color: #ffffff;
			font-size: #{24upx};
			line-height: #{60upx};
			text-align: center;
		}
		
		.down {
			margin-top: #{12upx};
		}
	}
	.goods-list {
		width: #{124upx};
		height: #{124upx};
		border-radius: #{62upx};
		background-color: rgba(51,51,51,.4);
		margin-left: #{20upx};
		position: relative;
		.image {
			width: #{68upx};
			height: #{78upx};
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
		}
	}
	.index {
		margin-left: #{20upx};
	}
	.cart {
		margin: #{0 30upx};
	}
	.but {
		text-align: center;
		position: relative;
		.icon {
			width: #{70upx};
			height: #{70upx};
			border-radius: #{35upx};
			background-color: rgba(51,51,51,.4);
			position: relative;
		}
		.image {
			width: #{38upx};
			height: #{36upx};
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
		}
		text {
			color: #ffffff;
			font-size: #{24upx};
			line-height: 1;
		}
	}
	.share {
		background: transparent;
		border: none;
		border-radius: 0;
		padding:0;
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
	}
	
	.scroll {
		width: #{690upx};
		height: #{240upx};
		position: fixed;
		left: 50%;
		bottom: #{157upx};
		transform: translate(-50%, 0%);
	}
	.scroll-view {
		height: calc(100% - #{23upx});
		background-color: #ffffff;
		border-radius: #{16upx};
		padding: #{0 25upx};
		.item-good {
			padding-top: #{25upx};
			.image-view {

				position: relative;
				>view {
					width: #{150upx};
					height: #{30upx};
					line-height: #{30upx};
					position: absolute;
					bottom: 0;
					font-size: #{18upx};
					color: #ffffff;
					text-align: center;
					background: linear-gradient(to left, #ffcb00, #ff9600);
				}
			}
		}
		.cover-pic {
			width: #{150upx};
			height: #{150upx};
		}
		.content {
			width: calc(100% - #{150upx});
			min-height: #{150upx};
			margin-bottom: #{25upx};
			padding-left: #{25upx};
		}
		.name {
			line-height: #{32upx};
			font-size: #{24upx};
			color: #303030;
			margin-top: #{8upx};
		}
		.pri-but {

			>.button {
				width: #{50upx};
				height: #{50upx};
				background-image: url("../../static/image/icon/add-to.png");
				background-size: 100% 100%;
				background-repeat: no-repeat;
				margin: #{0 4upx 0 0};
				border-radius: #{25rpx};
				background-color: transparent;
			}
			.pri {
				line-height: #{21upx};
				margin-top: #{9upx};
			}
			.price {
				color: #ff4544;
				font-size: #{21upx};
				line-height: 1;
			}
			.original {
				color: #999999;
				font-size: #{17upx};
				line-height: 1;
				text-decoration: line-through;
				margin-left: #{15upx};
			}
		}
		.member-price {
			margin-right: #{12upx};
		}
	}
	.triangle {
		width: #{40upx};
		border-top: #{23upx} solid #ffffff;
		border-bottom: #{23upx} solid transparent;
		border-left: #{23upx} solid transparent;
		border-right: #{23upx} solid transparent;
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
	}
	.close {
		position: fixed;
		top: #{26upx};
		right: #{26upx};
		width: #{70upx};
		height: #{70upx};
		z-index: 1406;
		border-radius: #{35upx};
		background-color: rgba(51,51,51,.4);
		.image {
			width: #{26upx};
			height: #{26upx};
			position:absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
		}
	}
	.swiper {
		position: relative;
	}
	.cover-view-marks {
		position: fixed;
		top: 0;
		right: 0;
		z-index: 1401;
	}

	.video {
		width: 100%;
		height: 100%;
		position: relative;
	}
	.pintuan {
		width: #{750upx};
		height: #{110upx};
		color: #ffffff;
		.single {
			background-color: #f39800;
			text-align: center;
			line-height: #{110upx};
		}
		.tuan {
			background-color: #ff4544;
			text-align: center;
			line-height: #{110upx};
		}
	}
</style>
